package servlets;

import dao.Userdao;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/login")
public class login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public login() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("name");
        String userpwd = request.getParameter("password");

        String isuser = request.getParameter("user");
        System.out.println(isuser);
        Userdao ud = new Userdao();
        if(isuser.equals("user") && ud.login(username, userpwd, "1")) {
            // 重定向到用户主界面
            request.getSession().setAttribute("name", username);   // SET Session
            response.sendRedirect("main.jsp?id=0");
        }
        else if(isuser.equals("shop") && ud.login(username, userpwd, "0")) {
            // 重定向到店长界面
            System.out.println("FSAFSDFDSAFDSFSda");
            request.getSession().setAttribute("name", username);   // SET Session
            response.sendRedirect("management.jsp");
        }
        else if(isuser.equals("admin") && ud.login(username, userpwd, "2")) {
            // 重定向到管理员界面
        }
        else {
            request.setAttribute("failed", "failed");//
            RequestDispatcher forword = request.getRequestDispatcher("login.jsp");
            forword.forward(request, response);
        }
    }
}